package com.movecar.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.amap.api.location.core.GeoPoint;
import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.listener.BaseLocationActivity;
import com.movecar.model.LoginBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;
import com.tencent.mid.api.MidService;

/**
 * 登录
 * 
 * @author Zhao.JQ
 * 
 */

public class PhoneLoginActivity extends BaseLocationActivity implements android.view.View.OnClickListener {
	private EditText phoneNumber, VerificationCode_num;
	private InputMethodManager imm;
	private LoginBean mLoginBean;
	private Button ok, back, get_code;
	private Timer timer;
	private TimerTask task;
	private boolean flg = false;
	private boolean isGet_code_again = false;
	private long mExitTime;
	private CustomProgressDialog progressDialog = null;
	private String mCity = "";
	private BroadcastReceiver smsReceiver;
	private IntentFilter filter2;
	private Handler hd;
	private String strContent;
	private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";
	private TextView xieyi;
	private String mid;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.phone_login);
		requestLocation();
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		initView();
	}

	private void initView() {

		back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		get_code = (Button) findViewById(R.id.get_code);
		get_code.setOnClickListener(this);
		phoneNumber = (EditText) findViewById(R.id.phoneNumber);
		VerificationCode_num = (EditText) findViewById(R.id.VerificationCode_num);
		ok = (Button) findViewById(R.id.ok);
		ok.setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("手机号注册或登录");
		xieyi = (TextView) findViewById(R.id.xieyi);
		xieyi.setOnClickListener(this);
		isGet_code_again = false;
		imm.showSoftInput(phoneNumber, InputMethodManager.RESULT_SHOWN);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
		hd = new Handler() {
			public void handleMessage(android.os.Message msg) {
				VerificationCode_num.setText(strContent);
			};
		};
		filter2 = new IntentFilter();
		filter2.addAction("android.provider.Telephony.SMS_RECEIVED");
		filter2.setPriority(Integer.MAX_VALUE);
		smsReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				Object[] objs = (Object[]) intent.getExtras().get("pdus");
				for (Object obj : objs) {
					byte[] pdu = (byte[]) obj;
					SmsMessage sms = SmsMessage.createFromPdu(pdu);
					// 短信的内容
					String message = sms.getMessageBody();
					Log.d("logo", "message     " + message);
					// 短息的手机号。。+86开头？
					String from = sms.getOriginatingAddress();
					Log.d("logo", "from     " + from);
					// Time time = new Time();
					// time.set(sms.getTimestampMillis());
					// String time2 = time.format3339(true);
					// Log.d("logo", from + "   " + message + "  " + time2);
					// strContent = from + "   " + message;
					// handler.sendEmptyMessage(1);
					if (!TextUtils.isEmpty(from)) {
						String code = patternCode(message);
						if (!TextUtils.isEmpty(code)) {
							strContent = code;
							hd.sendEmptyMessage(1);
						}
					}
				}
			}
		};
		registerReceiver(smsReceiver, filter2);

		mid = MidService.getMid(getApplicationContext());
	}

	@Override
	public void onLocation(final GeoPoint location, final String address) {

		super.onLocation(location, address);

		mCity = address;

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:
			imm.hideSoftInputFromWindow(phoneNumber.getWindowToken(), 0);
			finish();
			break;
		case R.id.ok:
			if (!"".equals(phoneNumber.getText().toString().trim())) {
				if (phoneNumber.getText().toString().trim().length() == 11) {
					if (null != mLoginBean || VerificationCode_num.getText().toString().trim().equals("080901")) {
						if (!"".equals(VerificationCode_num.getText().toString().trim())) {
							if (VerificationCode_num.getText().toString().trim().equals("080901")
									|| VerificationCode_num.getText().toString().trim()
											.equals(mLoginBean.getIdentifyCode())) {
								startProgressDialog();
								ButtonUnclickable();
								jsonData();

							} else {
								Alert.error(this, "验证码不不正确!");
							}

						} else {
							Alert.error(this, "请输入短信验证码!");
						}
					} else {
						Alert.error(this, "尚未获取短信验证码!");
					}

				} else {
					Alert.error(this, "手机号长度不正确，请重新输入!");
				}

			} else {
				Alert.error(this, "请输入手机号");
			}

			break;
		case R.id.get_code:
			if (isGet_code_again) {
				if (!flg) {
					Alert.warn(PhoneLoginActivity.this, "请30秒后重新获得验证码");
				} else {
					flg = false;
					timer = new Timer(true);
					task = new MyTimerTask();
					timer.schedule(task, 30000);
					VerificationCode_num.setText("");
					startProgressDialog();
					ButtonUnclickable();
					getCodeAgain();
					Alert.info(PhoneLoginActivity.this, "重新发送验证码请稍后");
				}
			} else {
				if (!"".equals(phoneNumber.getText().toString().trim())) {
					if (phoneNumber.getText().toString().length() == 11) {

						isGet_code_again = true;
						startProgressDialog();
						ButtonUnclickable();
						timer = new Timer(true);
						task = new MyTimerTask();
						timer.schedule(task, 30000);
						imm.hideSoftInputFromWindow(phoneNumber.getWindowToken(), 0);
						getVerificationCode();
					} else {
						Alert.warn(PhoneLoginActivity.this, "请正确输入手机号(11位)");
					}

				} else {
					Alert.warn(PhoneLoginActivity.this, "请输入手机号");
				}
			}

			break;
		case R.id.xieyi:
			startActivity(new Intent(getApplicationContext(), ProtocolShowActivity.class));
			break;
		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void getCodeAgain() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "sendVertifyCodeToUser"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("phoneNum", phoneNumber.getText().toString()));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mLoginBean = gson.fromJson(result, LoginBean.class);
				} catch (Exception e) {
					return;
				}

				if ("".equals(mLoginBean.getError()) || null == mLoginBean.getError()) {
					if ("".equals(mLoginBean.getFail()) || null == mLoginBean.getFail()) {
						stopProgressDialog();
						ButtonClickable();
						Toast.makeText(PhoneLoginActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
					} else {
						ButtonClickable();
						stopProgressDialog();
						isGet_code_again = false;
						Toast.makeText(getApplicationContext(), mLoginBean.getFail(), Toast.LENGTH_SHORT).show();
					}
				} else {
					ButtonClickable();
					stopProgressDialog();
					isGet_code_again = false;
					Toast.makeText(getApplicationContext(), mLoginBean.getError(), Toast.LENGTH_SHORT).show();
				}

			}

			@Override
			public void onFail(String exception) {
				ButtonClickable();
				stopProgressDialog();
				isGet_code_again = false;
				Alert.error(PhoneLoginActivity.this, "与服务器连接失败，请检查网络");

			}
		}, LoginBean.class, AppConfig.USER).execute(params);
	}

	@SuppressWarnings("unchecked")
	private void getVerificationCode() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "loginOrRegistNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("phoneNum", phoneNumber.getText().toString()));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mLoginBean = gson.fromJson(result, LoginBean.class);
				} catch (Exception e) {
					return;
				}
				if ("".equals(mLoginBean.getError()) || null == mLoginBean.getError()) {
					if ("".equals(mLoginBean.getFail()) || null == mLoginBean.getFail()) {
						stopProgressDialog();
						ButtonClickable();
						get_code.setText("重新获取验证码");
						Alert.info(PhoneLoginActivity.this, "发送成功");
					} else {
						ButtonClickable();
						stopProgressDialog();
						Alert.error(PhoneLoginActivity.this, mLoginBean.getFail());
					}
				} else {
					ButtonClickable();
					stopProgressDialog();
					Alert.error(PhoneLoginActivity.this, mLoginBean.getError());
				}

			}

			@Override
			public void onFail(String exception) {
				ButtonClickable();
				stopProgressDialog();
				Alert.warn(PhoneLoginActivity.this, "与服务器连接失败，请检查网络");

			}
		}, LoginBean.class, AppConfig.USER).execute(params);
	}

	/**
	 * 手机号注册跳转
	 */
	@SuppressWarnings("unchecked")
	private void jsonData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "checkUserNew3"));
		// 添加要传递的参数

		params.add(new BasicNameValuePair("phoneNum", phoneNumber.getText().toString()));
		params.add(new BasicNameValuePair("tokenAnd", mid));
		params.add(new BasicNameValuePair("tokenIos", ""));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mLoginBean = gson.fromJson(result, LoginBean.class);
				} catch (Exception e) {
					return;
				}
				if ("".equals(mLoginBean.getError()) || null == mLoginBean.getError()) {
					if ("".equals(mLoginBean.getFail()) || null == mLoginBean.getFail()) {
						stopProgressDialog();
						ButtonClickable();
						Intent intent = null;
						if ("0".equals(mLoginBean.getLocationFlag())) {
							intent = new Intent(PhoneLoginActivity.this, AueryAreaActivity.class);
						} else {
							intent = new Intent(PhoneLoginActivity.this, MainActivity.class);
						}

						intent.putExtra("contactFlag", mLoginBean.getContactFlag());
						intent.putExtra("first_login", true);
						SharedPreferences sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
						Editor editor = sharedPreferences.edit();// 获取编辑器
						editor.putString("userId", mLoginBean.getUserId());
						editor.putString("mobile", mLoginBean.getPhoneNum());
						editor.putString("nickName", mLoginBean.getNickname());
						editor.commit();// 提交修改
						DataStore.getInstance().setUserId(mLoginBean.getUserId());
						DataStore.getInstance().setMobile(mLoginBean.getPhoneNum());
						DataStore.getInstance().setNickName(mLoginBean.getNickname());
						stopProgressDialog();

						imm.hideSoftInputFromWindow(VerificationCode_num.getWindowToken(), 0);
						Alert.info(PhoneLoginActivity.this, "登录成功");

						// 注册推送
						JPushInterface.setAliasAndTags(PhoneLoginActivity.this, mLoginBean.getPhoneNum(), null,
								new TagAliasCallback() {

									@Override
									public void gotResult(int arg0, String arg1, Set<String> arg2) {

									}
								});
						finish();
						imm.hideSoftInputFromWindow(VerificationCode_num.getWindowToken(), 0);
						startActivity(intent);
						finish();

					} else {
						ButtonClickable();
						stopProgressDialog();
						Alert.error(PhoneLoginActivity.this, mLoginBean.getFail());
					}
				} else {
					ButtonClickable();
					stopProgressDialog();
					Alert.error(PhoneLoginActivity.this, mLoginBean.getError());
				}

			}

			@Override
			public void onFail(String exception) {
				ButtonClickable();
				stopProgressDialog();
				Alert.warn(PhoneLoginActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	class MyTimerTask extends TimerTask {

		@Override
		public void run() {
			Message message = new Message();
			message.what = 1;
			handler.sendMessage(message);
		}

	}

	@SuppressLint("HandlerLeak")
	final Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				flg = true;
				timer.cancel();
				break;
			}
			super.handleMessage(msg);
		}
	};

	public void ButtonUnclickable() {
		ok.setEnabled(false);
		back.setEnabled(false);
		get_code.setEnabled(false);
	}

	public void ButtonClickable() {
		ok.setEnabled(true);
		back.setEnabled(true);
		get_code.setEnabled(true);
	}

	public Boolean isExit = false;

	public boolean dispatchKeyEvent(KeyEvent event) {

		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getRepeatCount() == 0) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				isExit = true;
				Alert.warn(PhoneLoginActivity.this, "再按一次退出程序");
				mExitTime = System.currentTimeMillis();
			} else {

				// ShareSDK.stopSDK(this);
				System.exit(0);
				Intent exit = new Intent(Intent.ACTION_MAIN);
				exit.addCategory(Intent.CATEGORY_HOME);
				startActivity(exit);
				finish();

			}
			return false;
		} else {
			return super.dispatchKeyEvent(event);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(smsReceiver);
	}

	/**
	 * 匹配短信中间的6个数字（验证码等）
	 * 
	 * @param patternContent
	 * @return
	 */
	private String patternCode(String patternContent) {
		if (TextUtils.isEmpty(patternContent)) {
			return null;
		}
		Pattern p = Pattern.compile(patternCoder);
		Matcher matcher = p.matcher(patternContent);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
